package com.duoketech.controller.weixin;

import com.duoketech.config.Constant;
import com.duoketech.controller.BaseController;
import com.duoketech.exception.ValidateException;
import com.duoketech.interceptor.WxCartInterceptor;
import com.duoketech.model.cart.Cart;
import com.duoketech.model.receiver.Receiver;
import com.duoketech.service.weixin.ReceiverService;
import com.duoketech.service.weixin.cart.WxCartService;
import com.duoketech.utils.PageUtil;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Page;

import java.util.List;

public class WxCartController extends BaseController {

    //@Before(WxCartInterceptor.class)
    public void cartList(){

        int memberId = getMemberId();
        List<Cart> cartList = WxCartService.ME.queryCartItemOfMine(memberId);
        Receiver receiver = ReceiverService.ME.queryDefaultReceiverBy(getMemberId());
        Page<Receiver> receivers = ReceiverService.ME.queryReceiverList(1,20,getMemberId());
        setAttr("receiver",receiver);
        setAttr("receivers",receivers.getList());
        setAttr("cartList",cartList);
        createToken(Constant.TOKEN_KEY);
        render("cart.html");
    }


    public void ajaxCartList(){
        int memberId = getMemberId();
        List<Cart> cartList = WxCartService.ME.queryCartItemOfMine(memberId);
        renderObject(cartList);
    }

    public void ajaxDoAddCart(){

        int productId = getParaToInt("id",0);
        try {
            WxCartService.ME.doAddCart(productId,getMemberId());
            renderSuccess("成功加入购物车");
        } catch (ValidateException e) {
            renderError(e.getMessage());
        }
    }


    public void ajaxDoDecreaseCart(){

        int productId = getParaToInt("id",0);
        try {
            WxCartService.ME.doDescreaseCart(productId,getMemberId());
            renderSuccess("成功加入购物车");
        } catch (ValidateException e) {
            renderError(e.getMessage());
        }
    }


    public void delCartItem(){
        String  ids = getPara("ids","");
        try {
            WxCartService.ME.delCartItem(ids);
            renderSuccess("删除物品成功");
        } catch (ValidateException e) {
            renderError(e.getMessage());
        }
    }
}
